package com.tf8.treasure.service.impl;

import com.tf8.treasure.common.Constant;
import com.tf8.treasure.entity.LtUser;
import com.tf8.treasure.entity.LtUserExample;
import com.tf8.treasure.entity.MultiMedia;
import com.tf8.treasure.mapper.LtUserMapper;
import com.tf8.treasure.service.LtUserService;
import com.tf8.treasure.service.MultiMediaService;
import com.tf8.treasure.utils.UuidTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class LtUserServiceImpl implements LtUserService {

    @Autowired
    private LtUserMapper ltUserMapper;
    @Autowired
    private MultiMediaService multiMediaService;

    @Override
    public LtUser saveOrUpdate(LtUser user) {
        LtUserExample example = new LtUserExample();
        example.createCriteria().andMobileEqualTo(user.getMobile());
        List<LtUser> ltUsers = ltUserMapper.selectByExample(example);
        user.setUpdateTime(new Date());
        user.setLoginTime(new Date());
        if (CollectionUtils.isEmpty(ltUsers)) {
            List<MultiMedia> byType = multiMediaService.findByType("3");
            if(!CollectionUtils.isEmpty(byType)){
                Collections.shuffle(byType);
                user.setPortraitUrl(byType.get(0).getPicUrl());
            }
            //添加
            String userId = UuidTools.getUuid();
            user.setUserId(userId);
            user.setCreateTime(new Date());
            user.setBalance(0);
            user.setGrade("1");
            user.setGradeExpTime(Constant.INITIAL_DATE);
            ltUserMapper.insertSelective(user);
            return user;
        }
        //修改
        ltUserMapper.updateByExampleSelective(user, example);
        return ltUsers.get(0);
    }
}
